
package com.qinglei.recoup.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qinglei.recoup.common.utils.JsonUtils;
import com.qinglei.recoup.system.dao.BedHealthDailyStatisticsMapper;
import com.qinglei.recoup.system.dao.BreathAnalysisMapper;
import com.qinglei.recoup.system.domain.*;
import com.qinglei.recoup.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

@Service
@Slf4j
public class BedSleepBreathImportDataServiceImpl extends ServiceImpl<BedHealthDailyStatisticsMapper, BedHealthDailyStatistics> implements BedSleepBreathImportDataService {

    @Autowired
    private BreathAnalysisService breathAnalysisService;

    @Autowired
    private SleepAnalysisService sleepAnalysisService;

    @Autowired
    private BedService bedService;

    //t_bed_health_daily_data 睡眠 心率 呼吸 体动  json 数据表
    @Autowired
    private BedHealthDailyDataService bedHealthDailyDataService;

    //睡眠呼吸数据表 t_bed_health_breath_daily_data
    @Autowired
    private BedHealthBreathDailyDataService bedHealthBreathDailyDataService;


    @Override
    public void BedSleepBreathImportData(List<BreathAnalysis> breathAnalysisList, List<SleepAnalysis> sleepAnalysisList, LocalDate statisticsDate) {
        {
            log.info("BedSleepBreathImportData开始处理:{}",statisticsDate);
            //-------------保存睡眠数据---------------------------------------------------------------------------------------------------------
            for (SleepAnalysis sleepAnalysis : sleepAnalysisList) {
                //0是有睡眠报告  1是没有睡眠报告
                if (sleepAnalysis == null || sleepAnalysis.getResultFlag() == null || 1 == sleepAnalysis.getResultFlag()) {
                    log.warn("importData4OneBed invalid data,data:{}", sleepAnalysis);
                    continue;
                }
                Bed bed = bedService.getBedBySn(sleepAnalysis.getDeviceId().toUpperCase());
                //判断是否有床位
                if (bed == null) {
                    log.warn("importData4OneBed bed not exist,data:{}", sleepAnalysis);
                    continue;
                }
                //判断雷达是否开启
                if (bed.getIsRadarOn() == 0) {
                    log.warn("importData4OneBed bed is off,data:{}", sleepAnalysis);
                    continue;
                }
                //满足条件开始删除  t_bed_health_daily_statistics
                this.remove(Wrappers.<BedHealthDailyStatistics>lambdaQuery()
                        .eq(BedHealthDailyStatistics::getBedId, bed.getId())
                        .eq(BedHealthDailyStatistics::getStatisticsDate, statisticsDate));

                BedHealthDailyStatistics bedHealthDailyStatistics = new BedHealthDailyStatistics();
                // 少活力指数 情绪指数  跌倒指数 还是定时任务
                BeanUtils.copyProperties(sleepAnalysis, bedHealthDailyStatistics);
                bedHealthDailyStatistics.setBedId(bed.getId());
                bedHealthDailyStatistics.setStatisticsDate(statisticsDate);
                //sleep_len_min   睡眠时长/min
                bedHealthDailyStatistics.setSleepDuration(sleepAnalysis.getSleepLenMin());//从入睡到起床之间的睡眠时长
                //sleep_len_valid_min 有效睡眠时长/min
                bedHealthDailyStatistics.setSleepLenValidMin(sleepAnalysis.getSleepLenValidMin().toString());
                //deep_time_len   深睡时长
                bedHealthDailyStatistics.setDeepSleepDuration(sleepAnalysis.getDeepTimeLen());//深睡
                //light_time_len  浅睡时长
                bedHealthDailyStatistics.setLightSleepDuration(sleepAnalysis.getLightTimeLen());//浅睡
                //wake_time_len   清醒时长
                bedHealthDailyStatistics.setClearSleepDuration(sleepAnalysis.getWakeTimeLen());//清醒
                //outbed_time_len 离床时常

                Integer duration = sleepAnalysis.getOutbedTimeLen();
                if (sleepAnalysis.getOutbedCount() > 0 && sleepAnalysis.getOutbedTimeLen() == 0) {
                    duration = 1;
                }
                //离床时间  outbed_time_len
                bedHealthDailyStatistics.setOutBedDuration(duration);
                //离床次数 outbed_count
                bedHealthDailyStatistics.setOutBedNum(sleepAnalysis.getOutbedCount());
                //体动次数 bodymove_count
                bedHealthDailyStatistics.setTurnOverNum(sleepAnalysis.getBodymoveCount());
                //睡眠得分 sleep_score
                if (null != sleepAnalysis.getSleepScore()) {
                    bedHealthDailyStatistics.setScore(sleepAnalysis.getSleepScore().longValue());
                }
                //睡眠报告结果标识 result_flag
                bedHealthDailyStatistics.setResultFlag(sleepAnalysis.getResultFlag());
                //上床时间 get_bed_time
                bedHealthDailyStatistics.setGetBedIdx(sleepAnalysis.getGetBedTime());
                //起床时间 out_bed_time
                bedHealthDailyStatistics.setLeaveBedIdx(sleepAnalysis.getOutBedTime());
                //入睡时间 sleep_time
                bedHealthDailyStatistics.setSleepStIdx(sleepAnalysis.getSleepTime());
                //晨醒时间 wake_time
                bedHealthDailyStatistics.setSleepEdIdx(sleepAnalysis.getWakeTime());
                this.save(bedHealthDailyStatistics);
                log.info("t_bed_health_daily_statistics import success, sn:{}, bedId:{}", sleepAnalysis.getDeviceId(), bed.getId());

                //-------------------------------------------------------------------------------------------------------------------------------------------------------------------

                if (sleepAnalysis.getResultFlag() != 0 || sleepAnalysis.getSleepLenMin() == 0) {
                    log.warn("importData4OneBed invalid data,data:{}", sleepAnalysis);
                    continue;
                }
                bedHealthDailyDataService.remove(Wrappers.<BedHealthDailyData>lambdaQuery().eq(BedHealthDailyData::getBedId, bed.getId()).eq(BedHealthDailyData::getStatisticsDate, statisticsDate));
                BedHealthDailyData bedHealthDailyData = new BedHealthDailyData();
                bedHealthDailyData.setBedId(bed.getId());
                bedHealthDailyData.setStatisticsDate(statisticsDate);
                //sleep_state 睡眠状态
                String sleepState = sleepAnalysis.getSleepState();
                List<Integer> sleepStateList = JsonUtils.jsonToList(sleepState, Integer.class);
                bedHealthDailyData.setSleepData(convertSleepData(sleepStateList).toString());

                //breath_bpm_min 呼吸BPM
                bedHealthDailyData.setBreathPhaseData(sleepAnalysis.getBreathBpmMin());
                //heart_bpm_min 心跳BPM
                bedHealthDailyData.setHeartPhaseData(sleepAnalysis.getHeartBpmMin());
                //bodymove_15min  15min体动次数详情
                bedHealthDailyData.setTurnOverData(sleepAnalysis.getBodymove15min());
                bedHealthDailyData.setCutStIdx(sleepAnalysis.getCutStIdx());
                bedHealthDailyData.setCutEdIdx(sleepAnalysis.getCutEdIdx());
                bedHealthDailyDataService.save(bedHealthDailyData);
                log.info("t_bed_health_daily_data import success, sn:{}, bedId:{}", sleepAnalysis.getDeviceId(), bed.getId());

            }
            //--------------------------------保存呼吸数据---------------------------------------------------------------------------------------------------
            for (BreathAnalysis breathAnalysis : breathAnalysisList) {
                Bed bed = bedService.getBedBySn(breathAnalysis.getDeviceId().toUpperCase());
                //判断是否有床位
                if (bed == null) {
                    log.warn("importData4OneBed bed not exist,data:{}", breathAnalysis);
                    continue;
                }
                //判断雷达是否开启
                if (bed.getIsRadarOn() == 0) {
                    log.warn("importData4OneBed bed is off,data:{}", breathAnalysis);
                    continue;
                }
                //0，-1，-2，         0有报告，其余两种都没有报告
                if (breathAnalysis.getFlagBreathReport() != null) {
                    //呼吸数据
                    QueryWrapper queryWrapper = new QueryWrapper();
                    queryWrapper.eq("bed_id", bed.getId());
                    queryWrapper.eq("statistics_date", statisticsDate);
                    bedHealthBreathDailyDataService.remove(queryWrapper);
                    BedHealthBreathDailyData bedHealthBreathDailyData = new BedHealthBreathDailyData();
                    bedHealthBreathDailyData.setBedId(bed.getId());
                    bedHealthBreathDailyData.setStatisticsDate(statisticsDate);
                    //低通气平均持续时长 lp_mean_len
                    bedHealthBreathDailyData.setHyponeaAverageTime(breathAnalysis.getLpMeanLen() == null ? Double.valueOf(0) : breathAnalysis.getLpMeanLen());
                    //呼吸暂停气平均持续时长 pause_mean_len
                    bedHealthBreathDailyData.setApneaAverageTime(breathAnalysis.getPauseMeanLen() == null ? Double.valueOf(0) : breathAnalysis.getPauseMeanLen());
                    //低通气总次数  低通气发生次数 lp_times
                    bedHealthBreathDailyData.setHyponeaTotalNumber(breathAnalysis.getLpTimes() == null ? 0 : breathAnalysis.getLpTimes());
                    //呼吸暂停总次数 呼吸暂停气发生次数 pause_times
                    bedHealthBreathDailyData.setApneaTotalNumber(breathAnalysis.getPauseTimes() == null ? 0 : breathAnalysis.getPauseTimes());
                    //AHI指数
                    bedHealthBreathDailyData.setAhi(breathAnalysis.getAhi() == null ? Double.valueOf(0) : breathAnalysis.getAhi());
                    //低通气时长  lp_details_min
                    bedHealthBreathDailyData.setHyponeaFrequencyStr(breathAnalysis.getLpDetailsMin());
                    //呼吸暂停时常 pause_details_min
                    bedHealthBreathDailyData.setApneaFrequencyStr(breathAnalysis.getPauseDetailsMin());
                    //呼吸报告标志位
                    bedHealthBreathDailyData.setFlagBreathReport(breathAnalysis.getFlagBreathReport());
                    //HRRP_section  数据切片的一维距离像数据
                    bedHealthBreathDailyData.setHrrpSectionStr(breathAnalysis.getHrrpSection());
                    // breath_phaseFIR_section 数据切片的FIR滤波后的呼吸相位数据
                    bedHealthBreathDailyData.setBreathPhaseSectionStr(breathAnalysis.getBreathPhasefirSection());
                    bedHealthBreathDailyData.setSliceTimeStr(breathAnalysis.getSliceTimeStr());
                    bedHealthBreathDailyData.setTimeStampMin(breathAnalysis.getTimeStampMin());
                    bedHealthBreathDailyData.setFigOssUrl(breathAnalysis.getFigOssUrl());
                    bedHealthBreathDailyDataService.save(bedHealthBreathDailyData);
                    log.info("t_bed_health_breath_daily_data import success, sn:{}, bedId:{}", breathAnalysis.getDeviceId(), bed.getId());
                }
            }
        }
        log.info("BedSleepBreathImportData处理结束:{}",statisticsDate);
    }

    private static List<Integer> convertSleepData(List<Integer> data) {
        if (CollectionUtils.isEmpty(data)) {
            return data;
        }
        for (int i = 0; i < data.size(); i++) {
            Integer val = data.get(i);
            if (val == null) {
                continue;
            }
            switch (val) {
                case 0:
                    // 离床
                    val = 4;
                    break;
                case 1:
                    // 清醒
                    val = 3;
                    break;
                case 2:
                    // 浅睡
                    val = 2;
                    break;
                case 3:
                    // 深睡
                    val = 1;
                    break;
            }
            data.set(i, val);
        }
        return data;
    }

}
